package com.uiotsoft.small.app.service.connect;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.uiotsoft.small.app.entity.AppClient;
import com.uiotsoft.small.app.service.AppBaseControl;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;

@Slf4j
public class AppLogin extends AppBaseControl {
    private final static String model = "mqttConnect";
    private final static String model2 = "localLogin";
    public AppLogin(AppClient appClient) {
        super(appClient);
    }

    public void loginToCloud() throws MqttException {
        //注册app,获取si,再app登录获取token
        appClient.appPasswordLogin();
        appClient.connect();
        //获取si/token才能初始化
    }

    public boolean loginToLocal() {
        String payload = "{\"areaCode\":\"\",\"loginType\":1,\"oem\":\"0X8001\",\"si\":\"\",\"userPwd\":\"\",\"qrCodePwd\":\"\",\"userUnique\":\"\",\"sn\":\"\",\"userName\":\"\"}";
        JSONObject payloadJson = JSONUtil.parseObj(payload);
        payloadJson.put("si",appClient.getSi());
        payloadJson.put("sn",appClient.getSn());
        payloadJson.put("userUnique",appClient.getUserUnique());
        publishToHost(model2,"localLogin",payloadJson);
        long start = System.currentTimeMillis();
        String topic;
        String result;
        while (true){
            //log.debug("******test*****{}",appClient.getMyMqttClient().toString());
            topic = appClient.getMyMqttClient().getTopic();
            result = appClient.getMyMqttClient().getResult();
            if (topic!= null && result != null){
                log.info("\n******客户端接收成功……\n******topic：{}:\n******content{}",topic,result);
                JSONObject resultJson = JSONUtil.parseObj(result);
                if (resultJson.getJSONObject("payload").getStr("code").equals("0")){
                    return true;
                }
            }
            long end = System.currentTimeMillis();
            if (end-start >10000){
                //return Result.fail(301,"超时",null);
                return false;
            }
           /* try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
        }
    }
}
